/**
 * 
 * 广州锐鹏计算机科技有限公司（www.ruipengkj.com）
 * 
 * 
 * Copyright (c) 2011-2012 RUIPENGKJ.Co.Ltd. All rights reserved.
 * 
 * */
package com.ruipengkj.view.baseDataView;

/**
 * 说明：
 * 商品管理
 * @Author：黄盛强
 * @Date：2012-03-20
 */
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.FileDialog;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTree;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.table.TableRowSorter;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

import com.ruipengkj.bean.TCommodity;
import com.ruipengkj.bean.TCommoditySuitDetail;
import com.ruipengkj.bean.TProductCatalog;
import com.ruipengkj.commons.BuildSpringApplication;
import com.ruipengkj.commons.base.query.PageIndex;
import com.ruipengkj.commons.base.query.PageModel;
import com.ruipengkj.commons.base.query.PageView;
import com.ruipengkj.commons.util.TabelUtil;
import com.ruipengkj.commons.util.Util;
import com.ruipengkj.commons.util.exportExcel.CommodityExportUtil;
import com.ruipengkj.component.JLabelJTextFieldComponent;
import com.ruipengkj.component.JPanelBoxLayoutComponent;
import com.ruipengkj.component.RPJButtonBlue;
import com.ruipengkj.component.RPJButtonGray;
import com.ruipengkj.component.RPJButtonRoundBlue;
import com.ruipengkj.component.RPJButtonRoundGray;
import com.ruipengkj.component.RPJButtonRoundOrager;
import com.ruipengkj.component.jpanel.QueryPanel;
import com.ruipengkj.component.jpanel.RepeatImagePanel;
import com.ruipengkj.component.jtree.OverwriteDefaultMutableTreeNode;
import com.ruipengkj.component.page.PageDelegale;
import com.ruipengkj.component.page.PagingComponent;
import com.ruipengkj.factory.ImageFactory;
import com.ruipengkj.model.DataCommodityModel;
import com.ruipengkj.service.TCommodityService;
import com.ruipengkj.service.TCommoditySuitDetailService;
import com.ruipengkj.service.TProductCatalogService;
import com.ruipengkj.view.base.BasePagePanel;

public class DataCommodityPanel extends BasePagePanel<TCommodity> implements DataCommodityQuery, 
		Runnable, PageDelegale, MouseMotionListener {

	private static final long serialVersionUID = 1L;
	private JButton queryButton; // 查询按钮
	private JButton surplusButton; // 库存量
	private JButton exportButton; // 导出
	private JButton printButton; // 打印
	private JButton addButton; // 添加
	private JButton updateButton; // 修改
	private JButton delButton; // 删除
	private JButton createCalogButton;//新建分类

	private JButton queryTypeButton; // 查询分类
	private JLabelJTextFieldComponent queryTF;// 查询分类
	private JLabelJTextFieldComponent commodityIDTF; // 编号
	private JLabelJTextFieldComponent commodityNameTF; // 名称
	private JLabelJTextFieldComponent commodityBarcodeTF; // 商品条码

	private JTable table;
	private JScrollPane tableJsp;
	private DataCommodityModel dataCommodityModel;
	private PagingComponent pagingComponent;// 翻页组件
	
	private DataTProductCatalogTreePanel dataTProductCatalogTreePanel;// 左边树
	private DataCommodityAddOrModifyDialog dataCommodityAddDialog;// 商品添加面板
	
	private JMenuItem addProductCatalogButton, deleteProductCatalogButton,
			updateProductCatalogButton, refreshProductCatalogButton;// 添加、删除、修改分类按钮、刷新
	private DataCommodityTProductCatalogAddDialog dataCommodityTProductCatalogAddDialog;// 产品分类添加面板

	private TCommodityService tCommodityService;// 商品
	private TCommoditySuitDetailService tCommoditySuitDetailService = BuildSpringApplication.getInstance().getTCommoditySuitDetailServiceImpl();
	private TProductCatalogService tProductCatalogService;//商品分类
	private TProductCatalog tProductCatalog;//商品分类
	private PageView<TCommodity> pageView;// 翻页主键 商品翻页

	private JPopupMenu treePopupMenu;
	private JProgressBar proBar;
	
	private JPanel waitComponentJPanel;
	private JPanel left_panel;
	
	private int queryAt = 0;//分类查询至第几条数据
	private int isSelect = -1;
	
	private JProgressBar jpb;//进度条
	
	public DataCommodityPanel() {
		jpb = new JProgressBar(0, 100);
		Util.setSize(jpb, 93, 15);
		
		waitComponentJPanel = new JPanelBoxLayoutComponent(new Component[]{new JLabel("数据加载中……"), jpb}, BoxLayout.Y_AXIS);
		waitComponentJPanel.setBackground(Color.white);
		waitComponentJPanel.setBorder(BorderFactory.createTitledBorder(""));
		
		this.setLayout(new BorderLayout());
		this.setBackground(Util.PANEL_COLOR);
		tProductCatalogService = BuildSpringApplication.getInstance().getTProductCatalogServiceImpl();
		tCommodityService = BuildSpringApplication.getInstance().getTCommodityServiceImpl();
		this.init();
		this.initListener();
		this.treeMousePopMenu();// 树 鼠标右键
	}
	private void init() {
		pageView = new PageView<TCommodity>();
		
		JSplitPane jsp = new JSplitPane();
		jsp.setOpaque(false);
		jsp.add(initLeft(), JSplitPane.LEFT, 0);
		jsp.add(initRight(), JSplitPane.RIGHT, 0);
		this.add(initTop(), BorderLayout.NORTH);
		this.add(jsp, BorderLayout.CENTER);
		// 排序
		TableRowSorter<DataCommodityModel> tableRowSorter = new TableRowSorter<DataCommodityModel>(
				dataCommodityModel);
		table.setRowSorter(tableRowSorter);
		queryAllTreeNode();
	}

	private JPanel initTop() {
		QueryPanel queryPanel=new QueryPanel("商店管理",ImageFactory.loadImage(ImageFactory.FUN_3_ICON_1));
		JPanel top_panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
		commodityIDTF = new JLabelJTextFieldComponent("商品编号：", 15);
		commodityNameTF = new JLabelJTextFieldComponent("商品名称：", 15);
		commodityBarcodeTF = new JLabelJTextFieldComponent("条形码：", 15);
		queryButton = new RPJButtonBlue("查询");
		
		surplusButton = new JButton("库存量");
		exportButton = new RPJButtonGray("导出");
		printButton = new JButton("打印");
		
		surplusButton.setEnabled(false);
		printButton.setEnabled(false);

		proBar=new JProgressBar();
		proBar.setMinimum(0);
		top_panel.add(commodityIDTF);
		top_panel.add(commodityNameTF);
		top_panel.add(commodityBarcodeTF);
		top_panel.add(queryButton);
//		top_panel.add(surplusButton);
		top_panel.add(exportButton);
		top_panel.add(proBar);
//		top_panel.add(printButton);
		queryPanel.addPanel(top_panel);
//		queryPanel.addBoxPanel(top_panel);
		return queryPanel;
	}

	private JPanel initLeft() {
		left_panel = uiFactory.createBorderJPanel();
		queryTF = new JLabelJTextFieldComponent("查询分类：", 10);
		
		queryTypeButton = new RPJButtonBlue("查询");
		JPanel jp1 = uiFactory.createFlowJPanel(FlowLayout.LEFT);
		jp1.add(queryTF);
		jp1.add(queryTypeButton);
		dataTProductCatalogTreePanel = new DataTProductCatalogTreePanel(jpb, false);
		dataTProductCatalogTreePanel.getTree().addMouseListener(this);
		
		createCalogButton=new RPJButtonRoundBlue("新建分类");
		JPanel jp2=uiFactory.createFlowJPanel(FlowLayout.LEFT);
		jp2.add(createCalogButton);
		left_panel.add(jp2,BorderLayout.NORTH);
		left_panel.add(dataTProductCatalogTreePanel, BorderLayout.CENTER);
		left_panel.add(jp1, BorderLayout.SOUTH);
		
		left_panel.setPreferredSize(new Dimension(236, 236));
		return left_panel;
	}

	private JPanel initRight() {
		JPanel right_panel = uiFactory.createBorderJPanel();
		
		pagingComponent = new PagingComponent();
		pagingComponent.setPageDelegale(this);
		dataCommodityModel = new DataCommodityModel();
		table = uiFactory.createRPJTable(dataCommodityModel, null, this, 30,JLabel.CENTER);
		table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		table.addKeyListener(this);
		tableJsp = uiFactory.createJScrollPane(table);

		JPanel gardPanel = new RepeatImagePanel(ImageFactory.loadImage(ImageFactory.DIALOG_DOWN_BG_1).getImage());
		gardPanel.setLayout(new GridLayout(1,2));
		JPanel jp1=uiFactory.createFlowJPanel(FlowLayout.LEFT);
		addButton = new RPJButtonRoundBlue("添加(Ctrl+A)");
		updateButton = new RPJButtonRoundGray("修改(Ctrl+M)");
		delButton = new RPJButtonRoundOrager("删除(Ctrl+D)");
		jp1.add(addButton);
		jp1.add(updateButton);
		jp1.add(delButton);
		gardPanel.add(jp1);
		gardPanel.add(pagingComponent);
		right_panel.add(tableJsp, BorderLayout.CENTER);
		right_panel.add(gardPanel, BorderLayout.SOUTH);
		return right_panel;
	}

	private void initListener() {
		queryTypeButton.addActionListener(this);
		addButton.addActionListener(this);
		addButton.registerKeyboardAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_A, KeyEvent.CTRL_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW);
		queryButton.addActionListener(this);
		updateButton.addActionListener(this);
		updateButton.registerKeyboardAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_M, KeyEvent.CTRL_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW);
		delButton.addActionListener(this);
		delButton.registerKeyboardAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_D, KeyEvent.CTRL_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW);
		exportButton.addActionListener(this);
		commodityIDTF.getText().addKeyListener(this);
		commodityNameTF.getText().addKeyListener(this);
		commodityBarcodeTF.getText().addKeyListener(this);
		createCalogButton.addActionListener(this);
		
		queryTF.getText().addKeyListener(this);
		dataTProductCatalogTreePanel.getTree().addMouseMotionListener(this);
	}

	
	//查询打开所有节点
	private void queryAllTreeNode() {
		left_panel.remove(dataTProductCatalogTreePanel);
		left_panel.add(waitComponentJPanel, BorderLayout.CENTER);
		left_panel.updateUI();
		dataTProductCatalogTreePanel.setDataCommodityQuery(this);
		queryCommodity();
	}
	
	@Override
	public void queryCommodity() {
		JTree tree = dataTProductCatalogTreePanel.getTree();
		while (queryAt < tree.getRowCount()) {
			if (tree.isCollapsed(queryAt) && !((OverwriteDefaultMutableTreeNode)tree.getPathForRow(queryAt).getLastPathComponent()).isLeaf()) {
				tree.expandRow(++queryAt-1);
				return;
			}
			++queryAt;
		}
		TreeNode root = (TreeNode)tree.getModel().getRoot();
		expandAll(tree, new TreePath(root));
		left_panel.remove(waitComponentJPanel);
		left_panel.add(dataTProductCatalogTreePanel, BorderLayout.CENTER);
		left_panel.updateUI();
	}
	//关闭所有节点
	private void expandAll(JTree tree, TreePath parent) {
		TreeNode node = (TreeNode)parent.getLastPathComponent();
		if (node.getChildCount() >= 0) {
			for (Enumeration<?> e = node.children(); e.hasMoreElements();) {
				TreeNode n = (TreeNode)e.nextElement();
				TreePath path = parent.pathByAddingChild(n);
				expandAll(tree, path);
			}
		}
		tree.collapsePath(parent);
	}


	//查询商品分类
	private void queryCommodityType() {
		JTree tree = dataTProductCatalogTreePanel.getTree();
		String keyWord = queryTF.getText().getText().trim();
		int queryAt = isSelect;//tree.getSelectionRows()==null ? 0:tree.getSelectionRows()[0];
		if (queryAt < 0)
			queryAt = 0;
		while (queryAt < tree.getRowCount()) {
			OverwriteDefaultMutableTreeNode node = (OverwriteDefaultMutableTreeNode) tree
					.getPathForRow(queryAt).getLastPathComponent();
			if (isSelect != queryAt)
			if (node.getNodeName().toLowerCase().contains(keyWord.toLowerCase())) {
				isSelect = queryAt;
				tree.setSelectionRow(queryAt);
				return;
			}
			if (tree.isCollapsed(queryAt)) {
				tree.expandRow(queryAt);
			}
			++queryAt;
		}

		if (isSelect > 0) {
			if (Util.showConfirmDialog("无结果，是否从头搜索？") == 0) {
				isSelect = -1;
				queryCommodityType();
			}
		} else {
			JOptionPane.showMessageDialog(null, "无结果!");
		}
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == queryTypeButton) {
			// 查询分类按钮
			JTree tree = dataTProductCatalogTreePanel.getTree();
			isSelect = tree.getSelectionRows()==null ? 0:tree.getSelectionRows()[0];
			queryCommodityType();
		} else if (e.getSource() == queryButton) {
			// 查询按钮
			this.termQuery(1);
		} else if (e.getSource() == addButton) {
			// 添加按钮
			dataCommodityAddDialog = new DataCommodityAddOrModifyDialog(null,
					"添加商品", true);
			dataCommodityAddDialog.showDialog(null,(OverwriteDefaultMutableTreeNode) dataTProductCatalogTreePanel.getTree().getLastSelectedPathComponent());
			if (dataCommodityAddDialog.isSuccess) {
				this.termQuery(1);
			}
		} else if (e.getSource() == updateButton) {
			// 修改按钮
			this.modifyCommodity();
		} else if (e.getSource() == delButton) {
			// 删除商品按钮
			this.deleteCommodity();
		} else if (e.getSource() == addProductCatalogButton) {
			// 添加商品分类按钮
			OverwriteDefaultMutableTreeNode selectedNode = null;
			if (dataTProductCatalogTreePanel.getTree().getSelectionRows() != null) {//当选中树节点添加时
				selectedNode = (OverwriteDefaultMutableTreeNode) dataTProductCatalogTreePanel
				.getTree().getLastSelectedPathComponent();
			}
			dataCommodityTProductCatalogAddDialog = new DataCommodityTProductCatalogAddDialog(
					null, "添加商品分类", true);
			dataCommodityTProductCatalogAddDialog.showDialog(selectedNode == null ? null:selectedNode.getNodeStringID(), true);
			if (dataCommodityTProductCatalogAddDialog.isSuccess) {
				OverwriteDefaultMutableTreeNode child = new OverwriteDefaultMutableTreeNode(
						dataCommodityTProductCatalogAddDialog.gettProductCatalog().getCatalogID(),
						dataCommodityTProductCatalogAddDialog.gettProductCatalog().getName(), 
						dataCommodityTProductCatalogAddDialog.gettProductCatalog().getDes()
				);
				OverwriteDefaultMutableTreeNode selectNode = (OverwriteDefaultMutableTreeNode) dataCommodityTProductCatalogAddDialog
						.getTreeNode();
				OverwriteDefaultMutableTreeNode parent = recursionNode(
						(OverwriteDefaultMutableTreeNode) dataTProductCatalogTreePanel
								.getTreeModel().getRoot(), selectNode);
				if (parent == null) {
					parent = (OverwriteDefaultMutableTreeNode) dataTProductCatalogTreePanel
							.getTreeModel().getRoot();
				}
				dataTProductCatalogTreePanel.getTreeModel().insertNodeInto(
						child, parent, parent.getChildCount());
			}
		} else if (e.getSource() == deleteProductCatalogButton) {
			// 删除商品分类按钮
			delNode();
		} else if (e.getSource() == updateProductCatalogButton) {
			// 修改商品分类按钮
			updataTreeNode(false);
		} else if (e.getSource() == refreshProductCatalogButton) {
			// 刷新商品分类
			dataTProductCatalogTreePanel.refreshModel();
			isSelect = -1;
			queryAllTreeNode();
		} else if(e.getSource()==createCalogButton){
			//新建分类
			addProductCatalogButton.doClick();
		}else if (e.getSource() == exportButton) {
			// 导出
			FileDialog fileDialog = new FileDialog(new JDialog(), "文件导出",
					FileDialog.SAVE);
			fileDialog.setVisible(true);
			String fileDir = fileDialog.getDirectory();
			String fileName = fileDialog.getFile();
			if (fileDir != null && !fileDir.equals("") && fileName != null
					&& !fileName.equals("")) {
				if (!fileName.toLowerCase().endsWith(".xls")) {
					if (fileName.lastIndexOf(".") != -1) {
						fileName = fileName.substring(0, fileName
								.lastIndexOf("."))
								+ ".xls";
					} else {
						fileName = fileName + ".xls";
					}
				}
				final String filePath=fileDir + fileName;
				new Thread(){
					public void run(){
						try {
							
							OverwriteDefaultMutableTreeNode treeNode=(OverwriteDefaultMutableTreeNode)dataTProductCatalogTreePanel.getTree().getLastSelectedPathComponent(); 
							if(null!=treeNode){
								tProductCatalog=new TProductCatalog(treeNode.getNodeStringID());
							}else{
								tProductCatalog=null;
							}
							final List<TProductCatalog> tProductCatalogList = new ArrayList<TProductCatalog>();
							queryCatalogTerm(tProductCatalogList, tProductCatalog);
							tProductCatalogList.add(tProductCatalog);
							
							
							List<TCommodity> list = tCommodityService.findTCommodityExportService(queryTerm(),tProductCatalogList);
							if (list != null && list.size() != 0) {
								exportButton.setEnabled(false);
								proBar.setMaximum(list.size());
								CommodityExportUtil.writeExcel(filePath,list, proBar);
								JOptionPane.showMessageDialog(null, "导出成功");
							} else {
								JOptionPane.showMessageDialog(null, "数据为空，导出失败");
							}
						} catch (Exception e1) {
							e1.printStackTrace();
							JOptionPane.showMessageDialog(null, "导出失败");
						}
						proBar.setValue(0);
						exportButton.setEnabled(true);
					}
				}.start();
			}

		}
	}

	private void updataTreeNode(boolean isAdd) {
		// 修改商品分类按钮
//		dataCommodityTProductCatalogAddDialog = new DataCommodityTProductCatalogAddDialog(
//				null, "修改商品分类", true);
//		OverwriteDefaultMutableTreeNode selectedNode = (OverwriteDefaultMutableTreeNode) dataTProductCatalogTreePanel
//				.getTree().getLastSelectedPathComponent();
//		dataCommodityTProductCatalogAddDialog.showDialog(selectedNode
//				.getNodeStringID(), isAdd);
//		if (dataCommodityTProductCatalogAddDialog.isSuccess) {
//			selectedNode.setNodeName(dataCommodityTProductCatalogAddDialog
//					.getName());
//			OverwriteDefaultMutableTreeNode newNode = new OverwriteDefaultMutableTreeNode(
//					selectedNode.getNodeStringID(),
//					dataCommodityTProductCatalogAddDialog
//							.gettProductCatalog().getName(), dataCommodityTProductCatalogAddDialog
//							.gettProductCatalog().getDes());
//			selectedNode.setUserObject(newNode);
//			dataTProductCatalogTreePanel.getTree().updateUI();
//		}
		OverwriteDefaultMutableTreeNode selectedNode = null;
		if (dataTProductCatalogTreePanel.getTree().getSelectionRows() != null) {//当选中树节点添加时
			selectedNode = (OverwriteDefaultMutableTreeNode) dataTProductCatalogTreePanel
			.getTree().getLastSelectedPathComponent();
		}
		dataCommodityTProductCatalogAddDialog = new DataCommodityTProductCatalogAddDialog(
				null, "添加商品分类", true);
		dataCommodityTProductCatalogAddDialog.showDialog(selectedNode == null ? null:selectedNode.getNodeStringID(), isAdd);
		if (dataCommodityTProductCatalogAddDialog.isSuccess) {
//			selectedNode.setNodeStringID(dataCommodityTProductCatalogAddDialog.gettProductCatalog().getCatalogID());
//			selectedNode.setNodeName(dataCommodityTProductCatalogAddDialog.gettProductCatalog().getName()); 
//			selectedNode.setText(dataCommodityTProductCatalogAddDialog.gettProductCatalog().getDes());
			TProductCatalog tProductCatalog = dataCommodityTProductCatalogAddDialog.gettProductCatalog();
			selectedNode.setUserObject(new OverwriteDefaultMutableTreeNode(tProductCatalog.getCatalogID(), tProductCatalog.getName(), tProductCatalog.getDes()));
			OverwriteDefaultMutableTreeNode selectNode = (OverwriteDefaultMutableTreeNode) dataCommodityTProductCatalogAddDialog
					.getTreeNode();
			OverwriteDefaultMutableTreeNode parent = recursionNode(
					(OverwriteDefaultMutableTreeNode) dataTProductCatalogTreePanel
							.getTreeModel().getRoot(), selectNode);
			if (parent == null) {
				parent = (OverwriteDefaultMutableTreeNode) dataTProductCatalogTreePanel
						.getTreeModel().getRoot();
			}
			dataTProductCatalogTreePanel.getTreeModel().removeNodeFromParent(selectedNode);//删除树节点
			dataTProductCatalogTreePanel.getTreeModel().insertNodeInto(selectedNode, parent, parent.getChildCount());
//			selectedNode.setParent(parent);
			dataTProductCatalogTreePanel.getTree().updateUI();
		}
	}
	//递归获取父节点
	private OverwriteDefaultMutableTreeNode recursionNode(OverwriteDefaultMutableTreeNode parent, OverwriteDefaultMutableTreeNode selectNode) {
		for (int i = parent.getChildCount() - 1; i >= 0; --i) {
			OverwriteDefaultMutableTreeNode child = (OverwriteDefaultMutableTreeNode)parent.getChildAt(i);
			if (child.getNodeStringID().equals(selectNode.getNodeStringID()))
				return child;
			child = recursionNode(child, selectNode);
			if (child != null)
				return child;
		}
		return null;
	}
	
	//递归删除子节点
	private void recursionDel(String parentID) {
		if (parentID == null || parentID.equals(""))
			return;
		TProductCatalog tProductCatalog = new TProductCatalog();//根据父节点查询分类
		tProductCatalog.setTProductCatalog(new TProductCatalog(parentID));
		try {
			List<TProductCatalog> tProductCatalogList = tProductCatalogService.findService(tProductCatalog);
			if (tProductCatalogList == null)
				return;
			for (int i = tProductCatalogList.size() - 1; i >= 0; --i) {
				recursionDel(tProductCatalogList.get(i).getCatalogID());//开始递归 删除
				TCommodity tCommodity = new TCommodity();//删除分类前，先把对应的商品，所对应的分类清空
				tCommodity.setTProductCatalog(tProductCatalogList.get(i));
				List<TCommodity> tCommodityServiceList = tCommodityService.findService(tCommodity);
				for (int j = tCommodityServiceList.size() - 1; j >= 0; --j) {
					tCommodityServiceList.get(j).setTProductCatalog(null);
					tCommodityService.modifyService(tCommodityServiceList.get(j));
				}
				tProductCatalogService.deleteService(tProductCatalogList.get(i).getCatalogID());//删除分类
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	// 删除节点的方法
	protected void delNode() {
		OverwriteDefaultMutableTreeNode selectedNode = (OverwriteDefaultMutableTreeNode) dataTProductCatalogTreePanel.getTree()
				.getLastSelectedPathComponent();
		if (selectedNode != null && selectedNode.getParent() != null) {
			// 判断选中的节点是否含有子节点
//			if (!selectedNode.isLeaf()) {
//				JOptionPane.showConfirmDialog(null, "当前分类尚有子分类，不能删除！");
//				return;
//			}
			if (!selectedNode.isLeaf()) {
				if (Util.showConfirmDialog("该分类存在子分类，确定删除吗？（若存在商品对应这些分类将清空该商品的分类）") != 0)
					return;
			} else if (Util.showConfirmDialog("确定删除此分类？（若存在商品对应此分类将清空该商品的分类）") != 0) {
				return;
			}
			recursionDel(selectedNode.getNodeStringID());//进入递归 删除数据库 删除子节点
			try {
				TCommodity tCommodity = new TCommodity();//删除分类前，先把对应的商品，所对应的分类清空
				tCommodity.setTProductCatalog(new TProductCatalog(selectedNode.getNodeStringID()));
				List<TCommodity> tCommodityServiceList = tCommodityService.findService(tCommodity);
				for (int j = tCommodityServiceList.size() - 1; j >= 0; --j) {
					tCommodityServiceList.get(j).setTProductCatalog(null);
					tCommodityService.modifyService(tCommodityServiceList.get(j));
				}
				tProductCatalogService.deleteService(selectedNode.getNodeStringID());//删除完所有子节点后删除父节点
			} catch (Exception e) {
				e.printStackTrace();
			}
			dataTProductCatalogTreePanel.getTreeModel().removeNodeFromParent(selectedNode);//删除树节点
		}
	}
	
	@Override
	public void mouseClicked(MouseEvent e) {
		if (e.getSource() == dataTProductCatalogTreePanel.getTree() || e.getSource() == dataTProductCatalogTreePanel) {
			if (e.getButton() == MouseEvent.BUTTON3) {
				// 鼠标右键
				if (e.getModifiers() == Event.META_MASK) {
					switch(dataTProductCatalogTreePanel.getTree().getLeadSelectionRow()) {
						case -1:
						case 0:
							treePopupMenu.remove(deleteProductCatalogButton);
							treePopupMenu.remove(updateProductCatalogButton);
							break;
						default:
							treePopupMenu.add(deleteProductCatalogButton, 1);
							treePopupMenu.add(updateProductCatalogButton, 2);
					}
					treePopupMenu.show(dataTProductCatalogTreePanel.getTree(), e.getX() + 10, e.getY() + 3);
//					}
					return;
				}
			}else{
    			this.termQuery(1);
    		}
		} else if (e.getSource() == table) {
			// 表格
			if (e.getClickCount() == 2) {
				// 修改商品
				this.modifyCommodity();
			}
		}
	}

	@Override
	public void keyPressed(KeyEvent e) {
		if (e.getSource() == commodityIDTF.getText()
				|| e.getSource() == commodityNameTF.getText()
				|| e.getSource() == commodityBarcodeTF.getText()) {
			// 会员名
			if (e.getKeyCode() == KeyEvent.VK_ENTER) {
				queryButton.doClick();
			} else if (e.getSource() == table) {
				if (e.getKeyCode() == KeyEvent.VK_DELETE) {
					// 删除商品
					this.deleteCommodity();
				}
			}
		} else if (e.getSource() == queryTF.getText() && e.getKeyCode() == KeyEvent.VK_ENTER) {
			queryTypeButton.doClick();
		}
	}

	@Override
	public void run() {
		this.termQuery(1);
	}

	private TCommodity queryTerm(){
		TCommodity tCommodity = new TCommodity();
		tCommodity.setCommodityID(commodityIDTF.getText().getText().trim());
		tCommodity.setName(commodityNameTF.getText().getText().trim());
		tCommodity.setBarcode(commodityBarcodeTF.getText().getText().trim());
		tCommodity.setTProductCatalog(tProductCatalog);
		return tCommodity;
	}
	
	//查询条件：分类，list储存条件
	private void queryCatalogTerm(List<TProductCatalog> tProductCatalogList, TProductCatalog parent) {
		if (tProductCatalog == null || tProductCatalog.getCatalogID() == null || tProductCatalog.getCatalogID().equals("")) {
			return;
		}
		List<TProductCatalog> list = null;
		try {
			TProductCatalog tProductCatalog = new TProductCatalog();
			tProductCatalog.setTProductCatalog(parent);
			list = tProductCatalogService.findService(tProductCatalog);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (list != null && list.size() != 0) {
			for (int i = list.size() - 1; i >= 0; --i) {
				tProductCatalogList.add(list.get(i));
				queryCatalogTerm(tProductCatalogList, list.get(i));
			}
		}
		return;
	}
	
	// 条件查询商品
	@Override
	protected void termQuery(final int currentPage) {
		OverwriteDefaultMutableTreeNode treeNode=(OverwriteDefaultMutableTreeNode)dataTProductCatalogTreePanel.getTree().getLastSelectedPathComponent(); 
		if(null!=treeNode){
			tProductCatalog=new TProductCatalog(treeNode.getNodeStringID());
		}else{
			tProductCatalog=null;
		}
		final List<TProductCatalog> tProductCatalogList = new ArrayList<TProductCatalog>();
		queryCatalogTerm(tProductCatalogList, tProductCatalog);
		tProductCatalogList.add(tProductCatalog);
		
		new Thread(){
			public void run(){
				tableJsp.getViewport().remove(table);
				tableJsp.getViewport().add(waitComponent);
				try {
					pageView.setCurrentPage(currentPage);
					PageModel<TCommodity> pageModel = tCommodityService.getScrollListService(pageView.getFirstResult(), pageView.getMaxResult(), queryTerm(), tProductCatalogList);
					pageView.setPageModel(pageModel);
					pageView.setPageIndex(PageIndex.getPageIndex(pageView.getPageCode(), pageView.getCurrentPage(), pageView.getTotalPage()));
					if (pageModel != null) {
						TabelUtil.clearTableRowSorter(table);
						dataCommodityModel.setRowData(pageModel.getResultList());
						SwingUtilities.invokeLater(new Runnable() {
							@Override
							public void run() {
								tableJsp.getViewport().remove(waitComponent);
								tableJsp.getViewport().add(table);
								TabelUtil.setJTabelAutoClumnWidth(table);
								pagingComponent.show();
							}
						});
					} else {
						// 没有订单数据
						tableJsp.getViewport().remove(waitComponent);
						tableJsp.getViewport().add(table);
						dataCommodityModel.clear();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
	}

	@Override
	protected PageView<TCommodity> getPageView() {
		return pageView;
	}

	// 删除商品
	private void deleteCommodity() {
		if (table.getRowCount() != 0) {
			int row = table.getSelectedRow();
			if (row != -1) {
				if (Util.showConfirmDialog("是否要删除选择记录") == 0) {
					String commodiID = (String) table.getValueAt(row, 0);
					try {
						List<TCommoditySuitDetail> list = tCommoditySuitDetailService.findService(
								new TCommoditySuitDetail(null, null, new TCommodity(commodiID)));
						for (int i = list.size() - 1; i >= 0; --i) {
							tCommoditySuitDetailService.deleteService(list.get(i).getId());
						}
						tCommodityService.deleteService(commodiID);
						JOptionPane.showMessageDialog(null, "删除成功");
						this.termQuery(1);
					} catch (Exception e1) {
						JOptionPane.showMessageDialog(null, "删除失败（请确定商品未被其他数据库表使用）");
						e1.printStackTrace();
					}
				}
			} else {
				JOptionPane.showMessageDialog(null, "请选择行在进行删除");
				return;
			}
		}
	}

	// 修改商品
	private void modifyCommodity() {
		if (table.getRowCount() != 0) {
			int row = table.getSelectedRow();
			if (row != -1) {
				String commodiID = (String) table.getValueAt(row, 0);
				try {
					TCommodity commodity = tCommodityService
							.getByIdService(commodiID);
					dataCommodityAddDialog = new DataCommodityAddOrModifyDialog(
							null, "修改商品", true);
					dataCommodityAddDialog.showDialog(commodity,null);
					
					if (dataCommodityAddDialog.isSuccess) {
						this.termQuery(1);
					}
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			} else {
				JOptionPane.showMessageDialog(null, "请选择行在进行修改");
				return;
			}
		}
	}

	// 树鼠标右键
	private void treeMousePopMenu() {
		treePopupMenu = new JPopupMenu();
		addProductCatalogButton = new JMenuItem("添加");
		deleteProductCatalogButton = new JMenuItem("删除");
		updateProductCatalogButton = new JMenuItem("修改");
		refreshProductCatalogButton = new JMenuItem("刷新");
		addProductCatalogButton.addActionListener(this);
		deleteProductCatalogButton.addActionListener(this);
		updateProductCatalogButton.addActionListener(this);
		refreshProductCatalogButton.addActionListener(this);
		treePopupMenu.add(addProductCatalogButton);
		treePopupMenu.add(deleteProductCatalogButton);
		treePopupMenu.add(updateProductCatalogButton);
		treePopupMenu.add(refreshProductCatalogButton);
	}

	@Override
	public void mouseDragged(MouseEvent e) {
		
	}
	
	//鼠标移动时
	@Override
	public void mouseMoved(MouseEvent e) {
		JTree tree = dataTProductCatalogTreePanel.getTree();
		TreePath treePath = tree.getPathForLocation(e.getX(), e.getY());
		if (treePath != null) {
			OverwriteDefaultMutableTreeNode treeNode = (OverwriteDefaultMutableTreeNode)treePath.getLastPathComponent();
			tree.setToolTipText(treeNode.getText() == "" ? null:treeNode.getText());
//			System.out.println(treeNode.getNodeName() + "   " + (treeNode.getText()==null?"":treeNode.getText()));
		} else {
			tree.setToolTipText(null);
		}
	}
	@Override
	public void clear() {
		dataCommodityModel.clear();
		queryTF.getText().setText("");// 查询分类
		commodityIDTF.getText().setText(""); // 编号
		commodityNameTF.getText().setText(""); // 名称
		commodityBarcodeTF.getText().setText(""); // 商品条码
	}
	
}
